import React, { PureComponent } from 'react';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Select } from 'antd';
import { InputNumberC, InputC } from '../../../comps';
const { Option } = Select;
const FormItem = Form.Item;
import { connect } from 'dva';
import styles from './style.less';
import BenchComponents from './benchComponents';

@Form.create()
@connect(({ BaselineInformationNewM }) => ({ BaselineInformationNewM }))
export default class OperateForm extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      isAfter: '', // 运算符默认单位
      isReq: false, // modal里运算符和运算值是否必填
      type: '', //基准类型
    };
  }
  componentDidMount() {
    this.props.onRef(this);
    if (this.props.isEdit) {
      this.setState({
        type: this.props.editObj.type,
      });
    } else {
      this.setState({
        type: '单一',
      });
    }
  }
  //运算值默认单位的控制
  onChangeOperator = (e) => {
    if (e === '+' || e === '-') {
      this.setState({
        isAfter: '(BP)',
      });
    } else {
      this.setState({
        isAfter: '',
      });
    }
  };
  // 基准类型变更
  onChangeEvery = (e) => {
    if (e && e !== this.state.type) {
      this.props.form.resetFields(['benchComponents']);
    }
    //运算值和运算符
    /**
     * 当基准类型选择自定义的时候 运算值和运算符都为不可填写
     * 自定义 运算值和运算符为必填
     */
    if (e === '单一') {
      this.setState({
        type: '单一',
      });
    } else if (e === '自定义') {
      this.setState({
        type: '自定义',
        isReq: true,
      });
    } else if (e === '复合') {
      this.setState({
        type: '复合',
      });
    } else if (e === '市值加权') {
      this.setState({
        type: '市值加权',
        isReq: false,
      });
    }
  };
  isRepeat = (arr) => {
    //判断数组里是否有相同的元素
    var hash = {};
    for (var i in arr) {
      if (hash[arr[i]]) {
        return true;
      }
      hash[arr[i]] = true;
    }
    return false;
  };
  // 基准构成校验
  checkControlValue = (rule, value, callback) => {
    const { isEdit, editObj } = this.props;
    const { type } = this.state;
    const tempType = isEdit ? editObj.type : type;
    const arrWeight = [];
    const arrWind = [];
    var flagFull = true; //是否填写完整
    var flagOne = true; // 子基准比例是否为一百或0
    var flagSame = true; // 成分是否有相同的
    var flagSum = true; //基准和是否为100
    if (tempType == '自定义' || tempType == '单一') {
      value.map((item) => {
        if (!item.wind) {
          flagFull = false;
        }
      });
    } else if (tempType == '市值加权') {
      value.forEach((item) => {
        if (item.wind) {
          arrWind.push(item.wind);
        } else {
          flagFull = false;
        }
      });
      if (this.isRepeat(arrWind)) {
        flagSame = false;
      }
    } else if (tempType == '复合') {
      value.forEach((item) => {
        if (item.benchId) {
          // 该条数据为自定义子基准
          if ((!item.weight && item.weight !== 0) || !item.benchId) {
            flagFull = false;
          } else {
            arrWind.push(item.benchId);
            arrWeight.push(item.weight);
          }
        } else {
          if ((!item.weight && item.weight !== 0) || !item.wind) {
            flagFull = false;
          } else {
            arrWind.push(item.wind);
            arrWeight.push(item.weight);
          }
        }
      });

      if (this.isRepeat(arrWind)) {
        flagSame = false;
      }
      let SumTemp = 0;
      arrWeight.forEach((item) => {
        if (Number(item) === 0 || Number(item) === 100) {
          flagOne = false;
        } else {
          SumTemp = SumTemp + Number(item);
        }
      });
      if (SumTemp !== 100) {
        flagSum = false;
      }
    }

    if (!flagFull) {
      callback('基准构成不能为空!');
    } else if (!flagSame) {
      callback('子基准不能重复!');
    } else if (!flagOne) {
      callback('复合类型子基准比例不能为0或100');
    } else if (!flagSum) {
      callback('子基准比例总和应为100');
    } else {
      callback();
    }
  };
  render() {
    const { isAfter, isReq, type } = this.state;
    const {
      editObj,
      isEdit,
      form: { getFieldDecorator },
    } = this.props;
    const formItemLayout = {
      labelCol: {
        span: 6,
      },
      wrapperCol: {
        span: 16,
      },
    };
    const formItemLayout2 = {
      labelCol: {
        span: 6,
      },
      wrapperCol: {
        span: 18,
      },
    };
    let tempArr = [];
    // 编辑回填
    if (editObj.children) {
      if (type == '复合') {
        editObj.children.map((item, index) => {
          if (item.benchId) {
            // 该条数据是自定义子基准
            tempArr.push({
              key: index + 1,
              weight: Number((item.weight - 0) * 100).toFixed(2),
              benchId: `【自定义】${item.benchId}`,
              wind: undefined,
            });
          } else {
            tempArr.push({
              key: index + 1,
              weight: Number((item.weight - 0) * 100).toFixed(2),
              wind: item.wind,
              benchId: undefined,
            });
          }
        });
      } else {
        editObj.children.map((item, index) => {
          tempArr.push({
            key: index + 1,
            weight: item.weight,
            wind: item.wind,
          });
        });
      }
    } else if (editObj.children === null) {
      tempArr.push({ key: 1, weight: editObj.weight, wind: editObj.wind });
    }
    const editDatas = isEdit ? tempArr || [] : [{ key: 1, weight: '', wind: '' }];
    return (
      <div>
        <Form style={{ marginBottom: '10px' }}>
          <Row style={{ marginBottom: '10px' }}>
            <InputC
              form={this.props.form} // form对象
              dataIndex={'benchName'}
              title={'基准名称'}
              disabled={isEdit == 'check' ? true : false}
              formItemLayout={formItemLayout}
              initialValue={editObj.benchName ? editObj.benchName : ''}
              rules={[{ required: true, message: '基准名称不能为空!' }]}
            />
          </Row>
          <Row style={{ marginBottom: '10px' }}>
            <FormItem label='基准类型' {...formItemLayout}>
              {getFieldDecorator(
                'type',
                {
                  initialValue: editObj.type ? editObj.type : '单一',
                  rules: [{ required: true, message: '基准类型不能为空!' }],
                },
                {},
              )(
                <Select onChange={(e) => this.onChangeEvery(e)} disabled={!isEdit ? false : true} placeholder='请选择'>
                  <Option key='单一' value='单一'>
                    单一
                  </Option>
                  <Option key='自定义' value='自定义'>
                    自定义
                  </Option>
                  <Option key='复合' value='复合'>
                    复合
                  </Option>
                  <Option key='市值加权' value='市值加权'>
                    市值加权
                  </Option>
                </Select>,
              )}
            </FormItem>
          </Row>
          <Row className={type == '复合' || type == '市值加权' ? styles.controlerror : ''} style={{ marginBottom: '10px' }}>
            <FormItem label='基准构成' {...formItemLayout2}>
              {getFieldDecorator('benchComponents', {
                rules: [
                  { required: true, message: '' },
                  {
                    validator: this.checkControlValue,
                  },
                ],
                initialValue: editDatas,
              })(<BenchComponents type={type} isEdit={isEdit} />)}
            </FormItem>
          </Row>
          <Row style={{ marginBottom: '10px' }}>
            <FormItem label='基准标签' {...formItemLayout}>
              {getFieldDecorator(
                'benchLabel',
                {
                  initialValue: editObj.benchLabel,
                  rules: [{ required: true, message: '基准标签不能为空!' }],
                },
                {},
              )(
                <Select disabled={isEdit == 'check' ? true : false}>
                  <Option value='公用' key='公用'>
                    公用
                  </Option>
                  <Option value='个人' key='个人'>
                    个人
                  </Option>
                </Select>,
              )}
            </FormItem>
          </Row>
          {type == '自定义' || type == '市值加权' || type == '复合' ? (
            <>
              <Row style={{ marginBottom: '10px' }}>
                <FormItem label='运算符' {...formItemLayout}>
                  {getFieldDecorator(
                    'operator',
                    {
                      initialValue: editObj.operator,
                      rules: [{ required: isReq, message: '运算符不能为空!' }],
                    },
                    {},
                  )(
                    <Select onChange={(e) => this.onChangeOperator(e)} disabled={isEdit == 'check' ? true : false}>
                      <Option key='+' value='+'>
                        +
                      </Option>
                      <Option key='-' value='-'>
                        -
                      </Option>
                      <Option key='*' value='*'>
                        *
                      </Option>
                      <Option key='/' value='/'>
                        /
                      </Option>
                    </Select>,
                  )}
                </FormItem>
              </Row>
              <Row style={{ marginBottom: '10px' }}>
                <InputNumberC
                  formItemLayout={formItemLayout}
                  title={`运算值${isAfter}`}
                  dataIndex={'shift'}
                  form={this.props.form}
                  disabled={isEdit == 'check' ? true : false}
                  min={0}
                  precision={2}
                  rules={[{ required: isReq, message: '运算值不能为空!' }]}
                  initialValue={editObj.shift}
                  addonAfter={isAfter}
                  style={{ width: '100%' }}
                />
              </Row>
            </>
          ) : (
            ''
          )}
        </Form>
      </div>
    );
  }
}
